package com.foreknow.controller;

import com.foreknow.model.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class ManagerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数 manager?q=list
        String method = req.getParameter("q");
        if("list".equals(method)) {
            list(req,resp);
        }else if("delete".equals(method)) {
            delete(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 服务器端向客户端响应的内容类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        // 设置客户端向服务器端发送请求的编码格式
        req.setCharacterEncoding("utf-8");
        //2. 在浏览器页面中输出内容
        PrintWriter out = resp.getWriter();
        //3. 调用service中的方法
        HttpSession session = req.getSession();
        GuestbookService service = new GuestbookServiceImpl();
        List<Guestbook> list = service.getQueryAll();
        //4. 需要将上面获取到的list集合保存到request,之后在list.jsp才能获取数据并显示
        session.setAttribute("list",list);
        //转发资源
        //req.getRequestDispatcher("/list.jsp").forward(req,resp);
        resp.sendRedirect("/JavaWebDemo2/list.jsp");
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 服务器端向客户端响应的内容类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        // 设置客户端向服务器端发送请求的编码格式
        req.setCharacterEncoding("utf-8");
        //2. 在浏览器页面中输出内容
        PrintWriter out = resp.getWriter();
        //3. 获取请求参数
        int id = Integer.parseInt(req.getParameter("id"));
        //4. 调用service的方法
        GuestbookService service = new GuestbookServiceImpl();
        boolean isRight = service.deleteById(id);
        if(isRight) {
            req.getRequestDispatcher("manager?q=list").forward(req,resp);
        }
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
